import { memo, useEffect } from "react";
import useSelectBorder from "../store/useSceneData";
import useGlobal from "../store/useGlobal";
import globalData from "../store/global";

const messageQueue: string[] = [];

const WebSocketNode = () => {
    const { setSelectId, setDeBug } = useSelectBorder()

    useEffect(() => {
        const socket = new WebSocket(`ws://${import.meta.env.VITE_LLM_API_URL.replace("http://", "")}/ws/${globalData.userId}`);

        socket.onopen = () => {
            console.log('WebSocket 连接成功');
        };

        socket.onmessage = (event) => {
            console.log('收到消息:', event.data);
            messageQueue.push(event.data);
        };

        socket.onerror = (error) => {
            console.error('WebSocket 错误:', error);
        };

        socket.onclose = () => {
            console.log('WebSocket 连接关闭');
        };

        const intervalId = setInterval(() => {
            const nodeId = messageQueue.shift();
            if (nodeId) {
                setDeBug(true);
                setSelectId(nodeId);
            }
        }, 500); // 每秒处理一次消息

        return () => {
            socket.close();
            clearInterval(intervalId)
        };
    }, []);

    return null
}

export default memo(WebSocketNode);